<template>
  <!-- 商品详情页面，，，图片上传，图片列表，，全部删除没弄好-->
  <div class="welMain">
    <h3 class="drawInfo">基本信息</h3>
    <el-form :inline="true" :model="formInline" ref="postForm" :rules="rulesInline" :disabled="isDisabled"
             :label-position="labelPosition" label-width="110px" class="searchDivFirst" size="mini">
      <div class="searchDivright">
        <el-form-item label=" 商品名称" prop="name">
          <el-input v-model="formInline.name" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品价格（元）">
          <el-input v-model="formInline.price" placeholder="请输入商品价格"></el-input>
        </el-form-item>
        <el-form-item label="有效时间">
          <el-date-picker type="datetime" placeholder="选择日期" v-model="formInline.effectiveTime"
                          style="width: 186px"></el-date-picker>
        </el-form-item>
      </div>
      <div class="searchDivright">
        <el-form-item label=" 商品编号">
          <el-input v-model="formInline.code" placeholder="请输入商品编号"></el-input>
        </el-form-item>
        <el-form-item label="商品简介">
          <el-input v-model="formInline.synopsis" placeholder="请输入商品简介"></el-input>
          <!--            <el-select v-model="formInline.exchangeType" style="width: 186px">-->
          <!--              <el-option-->
          <!--                v-for="item in  exchangeTypeOption "-->
          <!--                :key="item.value"-->
          <!--                :label="item.label"-->
          <!--                :value="item.value">-->
          <!--              </el-option>-->
          <!--            </el-select>-->
        </el-form-item>
        <el-form-item label="排序编号">
          <el-input v-model="formInline.sortNumber" placeholder="请输入排序编号"></el-input>
        </el-form-item>
      </div>
      <!--图片上传 searchDivleft-->
      <div class="searchDivleft">
        <el-form-item label="图片" class="uploadPic">
          <el-avatar shape="square" :size="115" :src="squareUrl"></el-avatar>
        </el-form-item>
      </div>
      <div class="searchDivleft">
      </div>
    </el-form>
    <h3 class="drawInfo">兑换信息</h3>
    <el-form :inline="true" :model="formInline" ref="postForm" :rules="rulesInline"
             :disabled="isDisabled" :label-position="labelPosition" label-width="110px" class="searchDivFirst"
             size="mini">
      <div class="searchDivright">
        <el-form-item label="是否兑换">
          <el-select v-model="formInline.redeemStatus" placeholder="请选择是否兑换" style="width: 186px">
            <el-option
              v-for="item in  redeemStatusOption "
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label=" 库存数量">
          <el-input v-model="formInline.inventoryCount" placeholder="请输入库存数量"></el-input>
        </el-form-item>
      </div>
      <div class="searchDivright">
        <el-form-item label="兑换积分" prop="redeemIntegral">
          <el-input v-model="formInline.redeemIntegral" placeholder="请输入兑换积分"></el-input>
        </el-form-item>
      </div>
      <div class="searchDivleft">
        <el-form-item label="积分+现金" prop="integralCash1">
          <el-input v-model="formInline.integral" placeholder="请输入积分 "></el-input>
        </el-form-item>
        <el-form-item label="  ">
          <el-input v-model="formInline.money" placeholder="请输入现金"></el-input>
        </el-form-item>
      </div>
      <div class="searchDivleft">
        <el-form-item label="兑换数量">
          <el-input v-model="formInline.redeemCount" placeholder="请输入兑换数量"></el-input>
        </el-form-item>
      </div>
    </el-form>
    <h3 class="drawInfo">抽奖信息</h3>
    <el-form :inline="true" :model="formInline" ref="postForm" :rules="rulesInline"
             :disabled="isDisabled" :label-position="labelPosition" label-width="110px" class="searchDivFirst"
             size="mini">
      <div class="searchDivright">
        <el-form-item label="是否抽奖商品">
          <el-select v-model="formInline.drawStatus" placeholder="请选择" style="width: 186px">
            <el-option
              v-for="item in  drawOption"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </div>
      <div class="searchDivright">
        <el-form-item label="抽奖积分">
          <el-input v-model="formInline.drawIntegral" placeholder="请输入抽奖积分"></el-input>
        </el-form-item>
      </div>
      <div class="searchDivleft">
        <el-form-item label="最多中奖数量">
          <el-input v-model="formInline.drawCount" placeholder="请输入最多中奖数量"></el-input>
        </el-form-item>
      </div>
      <div class="searchDivleft">
        <el-form-item label="抽奖概率" style="display: flex">
          <el-input v-model="formInline.drawProbability1" style="width: 80px"></el-input>
          <span>/</span>
          <el-input v-model="formInline.drawProbability2" style="width: 80px"></el-input>
        </el-form-item>
      </div>
    </el-form>
    <h3 class="drawInfo">第二步：图片设置（必填）</h3>
    <div>
      <div class="lastDivTitle">列表第一张图为主图，建议最小尺寸1300“900(宽"高)，大小500K内</div>
      <div class="buttonDiv">
        <el-button class="buttonStyle" type="primary" size="mini" @click="ImgUploadList">图片列表</el-button>
        <div class="notBlock">必填</div>
        <el-button class="buttonStyle" type="primary" size="mini" @click="handleCreate">{{title}}</el-button>
<!--        <el-button class="buttonStyle" type="primary" size="mini"   @click="handleAllDelete">全部删除</el-button>-->
      </div>
    </div>
    <el-dialog
      title="图片上传"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose">
      <div class="dialogDiv">
        <el-upload
          list-type="picture-card"
          action="#"
          :show-file-list="true"
          :auto-upload="false"
          :on-change="fileChange"
          :file-list="fileList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove">
          <i slot="default" class="el-icon-plus"></i>
          <div slot="file" slot-scope="{file}">
            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
            <span class="el-upload-list__item-actions">
                     <span class="el-upload-list__item-preview"
                           @click="handlePictureCardPreview(file)">
                        <i class="el-icon-zoom-in"></i>
                        </span>
                           <span
                             v-if="!disabled"
                             class="el-upload-list__item-delete"
                             @click="handleRemove(file)">
                           <i class="el-icon-delete"></i>
                            </span>
                         </span>
          </div>
        </el-upload>
        <div class="dialogButton">
          <el-button @click="handleCansle">取 消</el-button>
          <el-button type="primary" @click="handleYes">确 定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {productsInsert, productsQueryById, productseEdit, commonUpload} from '@/api/api.js';
  import axios from 'axios';
  import {Unix_timeStamp} from '@/utils/public.js';
  import {drawOption,exchangeTypeOption,redeemStatusOption} from '@/utils/dictionary.js';
  export default {
    data() {
      return {
        dialogVisible: false,
        squareUrl: '',
        redeemStatusOption:redeemStatusOption,
        drawOption:drawOption,
        exchangeTypeOption:exchangeTypeOption,
        rulesInline: {
          name: [
            {required: true, message: '请输入商品名称', trigger: 'blur'},
            {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
          ],
          redeemIntegral: [
            {required: true, message: '请输入兑换积分', trigger: 'blur'}
          ],
          integralCash1: [
            {required: true, message: '请输入积分', trigger: 'blur'}
          ],
        },
        isDisabled: false,
        formInline: {
          endTime: "",
          beginTime: '',
          name: '',
          current: 1,
          size: 10,
          drawStatus: "",
          code: '',
          effectiveTime:"",
          drawProbability2: '',
          drawProbability1: '',
          integralCash1: "",
          integralCash2: ''
        },
        total: 1,
        currentPage: 1, // 分页数据
        pageSize: 10,
        tableData: [],
        labelPosition: 'right',
        api_url: '',
        showImg: true,
        dialogImageUrl: '',
        noneUploadImg: false,
        fileList: [],
        disabled: '',
        title: "新增",
        attachList: [],//存放图片的attachId
        arrayList: []
      }
    },
    created() {
      this.api_url = axios.defaults.baseURL
      if (this.$route.query.id) {
        this.title = "保存";
        this.getQueryId()
      }
    },
    methods: {
      //handleAllDelete(){},
      handleCansle() {
        this.arrayList = []
        this.dialogVisible = false
      },
      handleYes() {
        this.attachList = this.arrayList.map(item => {
          this.attachList.push({attachmentId: item.attachmentId})
        })
        this.formInline.img = this.arrayList[0].attachmentId;
        this.squareUrl = this.arrayList[0].fileName;
        this.dialogVisible = false
      },
      /** 多图片上传*/
      ImgUploadList() {
        this.dialogVisible = true;
      },
      //关闭弹出框
      handleClose() {
      },
      /** 详情，获取到页面参数，isDisabled==true当是发布状态不可修改 */
      getQueryId() {
        productsQueryById(this.$route.query.id).then(response => {
          if (response.code === 0) {
            this.fileList = response.data.attachs.map(item => ({
              url: item.fileName, // 注意这里的key应该是'url'而非'fileName'
              status: 'done', // 标记为已上传状态
            }));
            this.attachList =response.data.attachs
            this.formInline = response.data;
            //主图地址  http://truck-mall-uat.stage.dev.saic-hongyan.com/
            this.squareUrl = response.data.imgUrl;
            if (response.data.drawProbability) {
              const drawProbability1 = response.data.drawProbability.split("/")[0];
              const drawProbability2 = response.data.drawProbability.split("/")[1];
              this.formInline.drawProbability1 = drawProbability1;
              this.formInline.drawProbability2 = drawProbability2;
            }
            if (response.data.integralCash) {
              const integralCash1 = response.data.integralCash.split("+")[0];
              const integralCash2 = response.data.integralCash.split("+")[1];
              this.formInline.integralCash1 = integralCash1;
              this.formInline.integralCash2 = integralCash2;
            }
            if (response.data.status === 1) {
              this.isDisabled = true
            }
          } else {
            this.$message({
              message: response.msg,
              type: 'warning'
            });
          }
        });
      },
      //海报的删除
      handleRemove(file, fileList) {
        const index = this.fileList.indexOf(file);
        // 如果在fileList中找到了文件，则执行删除操作
        if (index > -1) {
          // 从fileList中移除文件
          this.fileList.splice(index, 1);
          // 根据相同的索引从attachList中移除元素
          if (index < this.attachList.length) {
            this.attachList.splice(index, 1);
          }
        } else {
          console.warn('File not found in fileList');
        }
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      //活动海报的选图
      fileChange(file, fileList) {
        // 将File对象转换为Blob
        const blob = new Blob([file.raw], {type: file.raw.type});
        commonUpload(blob, file.raw.name).then(response => {
          if (response.code === 0) {
            //将所有的图片，放到一个list
            this.arrayList.push(response.data)
          } else {
            this.$message({
              message: response.msg,
              type: 'warning'
            });
          }
        });
        this.fileList = fileList
        this.picList = this.fileList
      },
      //新增
      handleCreate() {
        if(this.formInline.effectiveTime){
          this.formInline.effectiveTime= Unix_timeStamp(this.formInline.effectiveTime)
        }
        this.formInline.integralCash = this.formInline.integralCash1 + '+' + this.formInline.integralCash2;
        this.formInline.drawProbability = this.formInline.drawProbability1 + '/' + this.formInline.drawProbability2
        this.formInline.attachs = this.arrayList
        this.$refs.postForm.validate((valid) => {
          if (valid) {
            if (this.$route.query.id) {//修改
              productseEdit(this.formInline).then(response => {
                if (response.code === 0) {
                  this.$message({
                    message: response.msg,
                    type: 'success'
                  });
                  this.$router.back(-1)
                } else {
                  this.$message({
                    message: response.msg,
                    type: 'warning'
                  });
                }
              });

            } else {//新增
              productsInsert(this.formInline).then(response => {
                if (response.code === 0) {
                  this.$message({
                    message: response.msg,
                    type: 'success'
                  });
                  this.$router.back(-1)
                } else {
                  this.$message({
                    message: response.msg,
                    type: 'warning'
                  });
                }
              });
            }

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      }
    },
    computed: {},
  }
</script>

<style lang="less" scoped>
  .welMain {
  }
.notBlock{
  color: orangered;
  font-size: 12px;
  margin-right:30px;

}
  .dialogDiv {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  .dialogButton {
    display: flex;
    margin-top: 10px;
  }

  .searchDivFirst {
    padding: 10px;
    border-bottom: 1px solid #eeeeee;
    display: flex;
    justify-content: space-between;
  }

  .searchDivleft {
    width: 25%;
    /*border : 1px solid #eeeeee;*/
  }

  /*.searchImg{*/
  /*  width: 30%;*/
  /*}*/
  .searchDivright {
    width: 25%;
    /*border : 1px solid #eeeeee;*/
  }

  .lastDivTitle {
    padding: 0 10px;
  }

  .buttonDiv {
    display:flex;
    padding: 10px 0px;
    align-items: center;
  }

  .buttonStyle {
    margin: 0px 5px 0px 10px;
  }

  .el-avatar {
    background-color: #fff;
    border: 1px solid #eeeeee;
  }

  .drawInfo {
    padding: 10px;
    color: #585555;
    border-bottom: 1px solid #eeeeee;
  }

  .uploadIcon ::v-deep .el-upload--picture-card {
    display: none !important; /* 上传按钮隐藏 */
  }

</style>
